import { Component, OnInit, ViewChild, ViewContainerRef, ComponentRef, ComponentFactoryResolver, EventEmitter } from '@angular/core';
import { HistoryChangeService } from './history-change.service'
import { environment } from '../../../../../../../src/environments/environment';
import * as _ from "lodash";
import * as flatpickr from 'flatpickr';
import { zh } from "flatpickr/dist/l10n/zh.js";
import { Util } from 'app/common/util';
import { TablePageComponent } from '../../table/table-page/table-page.component';


@Component({
  selector: 'app-history-change',
  templateUrl: './history-change.component.html',
  styleUrls: ['./history-change.component.scss'],
  providers: [HistoryChangeService]
})
export class HistoryChangeComponent implements OnInit {

  //查询历史变更记录列表
  @ViewChild("qdiihistoryTablePage", { read: ViewContainerRef })
  qdiihistoryTablePage: ViewContainerRef;
  tablePageComponent: ComponentRef<TablePageComponent>;
  public nQdIds: any;
  public listData: any = [];
  public cloneList: any = [];
  //全选按钮
  public isCheckedAll: any = false;
  public getBody: any = {
    pageIndex: 1,
    pageSize: 50,
    nQdIds: '',
    sOprDateStart: '',
    sOprDateEnd: ''
  }

  //分页配置
  public listPageInfo = {
    currentPageNum: 1,
    pageSize: 50,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };
  // 条数分页
  sizeChange(pageSize: number) {
    if (pageSize !== this.listPageInfo.pageSize) {
      this.listPageInfo.pageSize = pageSize;
      this.loadlist();
    }
  }
  // 列表分页
  pageNavigation(currentPageNum: number) {
    this.listPageInfo.currentPageNum = currentPageNum;
    this.loadlist(this.listPageInfo.currentPageNum, this.listPageInfo.pageSize);
  }
  constructor(
    public resolver: ComponentFactoryResolver,
    public historyChangeService: HistoryChangeService,
  ) { }

  ngOnInit() {

    // 初始化日期控件
    flatpickr.localize(zh);
    this.loadlist();
  }

  loadlist(pageNum?, pageSize?) {
    let that = this;
    if (Util.dateOrder(this.getBody.sOprDateStart, this.getBody.sOprDateEnd)) {
      console.log(this.nQdIds);
      that.getBody.nQdIds = this.nQdIds;
      // 查询条件转码
      this.getBody.pageIndex = pageNum ? pageNum : this.listPageInfo.currentPageNum;
      this.getBody.pageSize = pageSize ? pageSize : this.listPageInfo.pageSize;
      console.log(that.getBody);
      this.historyChangeService.list(this.getBody).subscribe(data => {
        if (data) {
          console.log(data);
          this.listData = data.list;
          this.cloneList = _.cloneDeep(data.list);
          this.controlDom();
          this.showTablePage(this.listData);
          this.listPageInfo.currentPageNum = data.pageNum;
          this.listPageInfo.totalPages = data.pages;
          this.listPageInfo.total = data.total;
          this.listPageInfo.startRow = data.startRow;
          this.listPageInfo.endRow = data.endRow;

        }
      })
    } else {
      window['swal']("提示", "开始日期 不能比 结束日期晚", "warning");
    }
  }
  exportExcel() {
    console.log("====================");
    console.log(this.getBody.sOprDateStart);
    console.log(this.getBody.sOprDateEnd);
    let that = this;
    if (Util.dateOrder(this.getBody.sOprDateStart, this.getBody.sOprDateEnd)) {
      let nQdIds = this.nQdIds;
      let sOprDateStart = this.getBody.sOprDateStart;
      let sOprDateEnd = this.getBody.sOprDateEnd;
      console.log(nQdIds);
      // console.log("===============");
      // let checkedItem = [];
      // _.forEach(this.listData, item => {
      //   if (item.isChecked) {
      //     checkedItem.push(item.nQdId);
      //   }
      // })
      // nQdIdList=checkedItem;
      // let converItem: any = checkedItem.join(',');
      // let getBody = {
      //   "nAuditNoList": converItem,
      //   "sFundType": this.annuityCheckBody.sFundType,
      //   "sFullName": this.annuityCheckBody.sFullName,
      //   "sFundCode": this.annuityCheckBody.sFundCode,
      //   "sModifyItem": this.annuityCheckBody.sModifyItem
      // }
      const iframe = window['$']("<iframe id='downloadiframe'>");
      iframe.attr('style', 'display:none');
      //  转码，兼容ie
      // getBody.sFullName = encodeURI(getBody.sFullName)
      iframe.attr('src', environment.server + '/pms/v1/riskmanage/qdiiJournal/export/exportHistoryChange?token=' + sessionStorage.getItem('token') + '&nQdIds=' + nQdIds + '&sOprDateStart=' + sOprDateStart + '&sOprDateEnd=' + sOprDateEnd);
      window['$']('body').append(iframe);
      setTimeout("$('#downloadiframe').remove()", 60000);
    } else {
      window['swal']("提示", "开始日期 不能比 结束日期晚", "warning");
    }
  }
  // 列表全选
  checkedAll() {
    if (this.isCheckedAll) {
      // 更新为全选
      _.forEach(this.listData, item => {
        item.isChecked = true;
      });
    } else {
      // 更新为不全选
      _.forEach(this.listData, item => {
        item.isChecked = false;
      });
    }
  }
  // 列表是否全选
  ctrlCheckAll() {
    let that = this;
    let checkList = [];
    _.forEach(this.listData, item => {
      if (item.isChecked == true) {
        checkList.push(item);
      }
    })
    if (checkList.length == this.listData.length) {
      this.isCheckedAll = true;
    } else {
      this.isCheckedAll = false;
    }
  }
  //根据编号是否相同操控dom
  controlDom() {
    let that = this;
    setTimeout(() => {
      if (this.listData != null && this.listData.length > 0) {
        for (let i = 0; i < that.listData.length - 1; i++) {
          if (that.listData[i].nQjId == that.listData[i + 1].nQjId) {
            _.forIn(that.listData[i], (item1, key1) => {
              let index1 = i + 1;
              let index2 = i + 2;
              let id1 = "#route-table tbody tr:nth-child(" + index2 + ") td div[id=" + key1 + "]";
              if (item1 == that.listData[i + 1][key1]) {
                // window['$'](id1).removeClass('font-color');
              } else {
                // window['$'](id1).addClass('font-color');
                that.cloneList[i + 1][key1] = 'red';
              }
            })
          }
        }
      } else {
        this.controlDom();
      }
    });
  }
  //查询历史变更记录列表
  showTablePage(item) {
    // 判断组件是否已创建，如果创建先注销
    if (this.tablePageComponent && this.tablePageComponent.instance) {
      this.tablePageComponent.destroy();
    }

    // 动态创建组件的实例
    const tablePageComponent = this.resolver.resolveComponentFactory(TablePageComponent);
    this.tablePageComponent = this.qdiihistoryTablePage.createComponent(tablePageComponent);
    this.tablePageComponent.instance.listData = item;
    this.tablePageComponent.instance.listType = '2';
    this.tablePageComponent.instance.setColor = this.cloneList;
  }
}
